﻿/// <reference path="/Js/jsUtil.js"/> 
/// <reference path="/Js/main.js"/> 
/**
* 
*/
Ext.require('Region.Js.Region_Module');
Ext.define("House.Js.Sells_View", {
    show: function (SellId) {
        var winDom;
        var mSell = getRemoteObject("/House/Services/House_Sells.asmx/Query?t=" + Math.random(), { id: SellId });
        var userObj = getRemoteObject("/RBAC/Services/RBAC_Users.asmx/Query", { id: mSell.AddUserId });
        var IsAllowDisplayPhoneNumber = RBAC.Js.RBAC_Module.SystemGetBool("House", "IsAllowDisplayPhoneNumber");
        if (!mSell) {
            $.messager.show("操作提示", "房源编号不存在");
            return;
        }

        var buttons = [];
        buttons.push({
            text: '上传图片',
            handler: function () {
                $("#uploadId", winDom).click();
            }
        });
        if (X_USER == mSell.AddUser) {
            if (mSell.ViewLevel > 0) {
                buttons.push({
                    text: '转私盘',
                    handler: function (btn) {
                        $.get("House/Services/House_Sells_Follows.asmx/Add", { HouseId: SellId, Follow: '转私盘', FollowHouseState: 0, ViewLevel: 2, ChgHouseViewLevel: 0, SuggestState: 0 }, function (r) {
                            switch ($(r).find("ServiceStateKeys").text()) {
                                case "Success":
                                    $.messager.show({ title: '操作提示', msg: "操作成功。" });
                                    btn.setText("转公盘").disable();;
                                    break;
                                case "TimeOut":
                                    break;
                                case "NoPermiss":
                                    $.messager.show({ title: '操作提示', msg: "没有权限。" });
                                    break;
                                default:
                                    break;
                            }
                        });
                    }
                });
            }
            else if (mSell.ViewLevel == 0) {
                buttons.push({
                    text: '转公盘',
                    handler: function (btn) {
                        $.get("House/Services/House_Sells_Follows.asmx/Add", { HouseId: SellId, Follow: '转公盘', FollowHouseState: 0, ViewLevel: 2, ChgHouseViewLevel: 2, SuggestState: 0 }, function (r) {
                            switch ($(r).find("ServiceStateKeys").text()) {
                                case "Success":
                                    $.messager.show({ title: '操作提示', msg: "操作成功。" });
                                    btn.setText("转私盘").disable();
                                    break;
                                case "NoPermiss":
                                    $.messager.show({ title: '操作提示', msg: "没有权限。" });
                                    break;
                                case "TimeOut":
                                    break;
                                default:
                                    break;
                            }
                        });
                    }
                });
            }
        }
       
        buttons = buttons.concat([

                {
                    text: '举报是中介',
                    handler: function () {
                        popMenu('/Tools/Js/AgentMobiles_Add', 0);
                    }
                },
                {
                    text: '跟进',
                    handler: function () {
                        popMenu('/House/Js/Sells_Follows_Add', 0, SellId, winDom);
                    }
                }, {
                    text: '收藏',
                    handler: function (a, b, c) {
                        var Sell_Favs_Add = Ext.create("House.Js.Sells_Favs_Add");
                        Sell_Favs_Add.show(0, SellId);
                    }
                }, {
                    text: "号码",
                    handler: function () {
                        var control = $("span[name=tdTel]", winDom);
                        if (control.css("visibility") == 'hidden') {
                            if (mSell.State == '4') {
                                if (RBAC.Js.RBAC_Module.CheckLimit('出售房源', '改') || RBAC.Js.RBAC_Module.CheckLimit('买卖合同', '增') || RBAC.Js.RBAC_Module.CheckLimit('买卖合同', '改')) {
                                    control.css("visibility", "visible");
                                }
                            } else {
                                control.css("visibility", "visible");
                            }
                            if (!control.attr("data-load")) {
                                control.attr("data-load", "true");
                                ///中介
                                var obj = getRemoteObject("/Tools/Services/Tools_AgentMobiles.asmx/QueryTel", { tel: mSell.CustomerTel });
                                if (obj) {
                                    control.append('[中介号码]');
                                } else {
                                    ///手机号码所在地
                                    $.get("Tools/Services/Tools_MobileArea.asmx/Query", { number: mSell.CustomerTel }, function (v) {
                                        control.append($(v).find("city").text());
                                    });
                                }
                            }
                        }
                        else
                            control.css("visibility", "hidden");
                    }
                }, {
                    text: "关闭",
                    handler: function () {
                        this.up("window").close();
                    }
                }
        ]);

        var win = Ext.create('Ext.window.Window', {
            title: '查看出售房源', height: 500, width: 900, modal: true,
            loader: {
                url: '/House/Templates/Sells_View.htm', autoLoad: true, scripts: true,
                listeners: {
                    load: function (obj, eOpts) {
                        winDom = obj.dom;
                        var Region_Module = Ext.create("Region.Js.Region_Module");
                        mSell.AreaName = Region_Module.AreaRowsObj[mSell.SellRegionArea].AreaName;
                        var BuildingObj = Region_Module.getBuildingObj(mSell.SellBuildingId);

                        mSell.BuildingName = BuildingObj.BuildingName;
                        mSell.StateName = X_SELLSTATE[mSell.State];
                        mSell.StateColor = X_SELLSTATE_COLOR[mSell.State];
                        mSell.ViewLevelName = X_VIEWLEVEL[mSell.ViewLevel];
                        mSell.BuildingAddr = BuildingObj.BuildingAddr;
                        if (mSell.GetPropertyDate) {
                            if (formatDate(mSell.GetPropertyDate).indexOf('1900') > -1) {
                                mSell.GetPropertyDate = '未知';
                            }else if (formatDate(mSell.GetPropertyDate).indexOf('2000') > -1) {
                                mSell.GetPropertyDate = '2007年以前';
                            } else {
                                mSell.GetPropertyDate = formatYear(mSell.GetPropertyDate);
                            }
                        } else {
                            mSell.GetPropertyDate = formatYear(mSell.GetPropertyDate);
                        }
                        mSell.AddTime = formatDate(mSell.AddTime);
                        //mSell.ChangeKey =( mSell.AddUserId == X_USEROBJ.UserId);
                        if (mSell.SellFace == -1) mSell.SellFaceName = '未知类型';
                        else
                            mSell.SellFaceName = X_HOUSEFACE[mSell.SellFace];
                        if (X_HOUSEFACE_NOTINGCHUWEI.indexOf(mSell.SellFace) > -1)
                            mSell.Display = "none";
                        else
                            mSell.Display = "inline";
                        mSell.DecorationName = X_DECORATEKEYS[mSell.Decoration];
                        mSell.DepartName = X_DEPARTS['_' + mSell.AddDepartId].DepartName;
                        if (IsAllowDisplayPhoneNumber) {
                            mSell.Mobile = userObj.UserMobile;
                        }
                        else mSell.Mobile = "";
                        var _tempId = win.getId();
                        mSell.TempId = _tempId;
                        var $win = $(".x-autocontainer-innerCt", "#" + _tempId);
                        var html = template('House_Sell_View', mSell);
                        $win.html(html);
                        reloadImages(SellId);

                        $(".fancybox-button", $win).fancybox({
                            helpers: {
                                title: {
                                    type: 'float'
                                }
                            },
                            afterLoad: function () {
                                $(".fancybox-overlay-fixed,.fancybox-overlay").css("z-index", 29999);
                            }
                        });

                        //上传图片
                        $("#uploadId", $win).change(function () {
                            upChangeEvent();
                        });
                        function upChangeEvent() {
                            $.ajaxFileUpload({
                                url: '/Services/upload_json.ashx?path=sells',
                                secureuri: false,
                                fileElementId: 'uploadId',
                                dataType: 'json',
                                success: function (data, status) {
                                    var data_obj = JSON.parse(data);

                                    $.post('/House/Services/House_Sells_Images.asmx/Add', {
                                        HouseType: 0, HouseId: SellId, id: 0,
                                        ImgUrl: "'{0}'".format(data_obj.url),
                                        ThumbImgUrl: "'{0}'".format(data_obj.min)
                                    }, function () {
                                        reloadImages(SellId);

                                        var $parent = $("input[name=imgFile]", $win).parent();
                                        $parent.empty();
                                        $parent.append("<input type=\"file\" name='imgFile' id=\"uploadId\"  />");
                                        $("#uploadId", $win).change(function () {
                                            upChangeEvent();
                                        });
                                    });
                                },
                                error: function (data, status, e) {
                                    console.log('error');
                                    return;
                                }
                            });
                        }
                        //变更钥匙房源
                        $(".data-key", "#" + _tempId).click(function () {
                            var _module = $(this);
                            var val = parseInt(_module.attr("data-value"));

                            $.get("/House/Services/House_Sells.asmx/ChangeKey", { HouseId: SellId }, function (a) {
                                var result = parseInt($(a).find("int").text());
                                switch (result) {
                                    case 1: //有
                                        _module.text('改为无钥匙');
                                        _module.prev().text('有');
                                        $.messager.show({ title: '操作提示', msg: "操作成功。" });

                                        //
                                        if ($(".ulHouseSell", $win).length > 0) {
                                            var _str = "<li>【{0}】[{1}][{3}]{2}</li>".format(X_USER, (new Date()).format("yy-MM-dd hh:mm"), "变更钥匙房源状态为:有钥匙",
                                            X_SELLSTATE[mSell.State]);
                                            $(".ulHouseSell", $win).prepend(_str);
                                        }
                                        break;
                                    case 0: //无
                                        _module.text('改为有钥匙');
                                        _module.prev().text('无');
                                        $.messager.show({ title: '操作提示', msg: "操作成功。" });
                                        //
                                        if ($(".ulHouseSell", $win).length > 0) {
                                            var _str = "<li>【{0}】[{1}][{3}]{2}</li>".format(X_USER, (new Date()).format("yy-MM-dd hh:mm"), "变更钥匙房源状态为:无钥匙",
                                            X_SELLSTATE[mSell.State]);
                                            $(".ulHouseSell", $win).prepend(_str);
                                        }
                                        break;
                                    default:
                                        $.messager.show({ title: '操作提示', msg: "操作失败。" });
                                        break;
                                }
                            });
                        });
                        // 百度地图API功能
                        try {
                            var lat = 31.781192779541;
                            var lng = 117.215980529785;
                            if (BuildingObj.BuildingLatitude) lat = parseFloat(BuildingObj.BuildingLatitude);
                            if (BuildingObj.BuildingLongitude) lng = parseFloat(BuildingObj.BuildingLongitude);

                            if (!BuildingObj.BuildingLatitude) {
                                $("#map" + _tempId).html("无此小区位置信息");
                            } else {
                                var map = new BMap.Map("map" + _tempId);            // 创建Map实例
                                var point = new BMap.Point(lng, lat);    // 创建点坐标

                                map.centerAndZoom(point, 14);                     // 初始化地图,设置中心点坐标和地图级别。
                                map.enableScrollWheelZoom();                            //启用滚轮放大缩小
                                var marker = new BMap.Marker(new BMap.Point(lng, lat));  // 创建标注
                                map.addOverlay(marker);              // 将标注添加到地图中
                                map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] }));     //2D图，卫星图
                                setTimeout(function () {
                                    map.centerAndZoom(point, 15);
                                }, 500);
                            }
                        } catch (e) { }
                        ///重新加载图片
                        function reloadImages(HouseId) {
                            getRemoteRows("/House/Services/House_Sells_Images.asmx/GetLists", { page: 1, rows: 20, HouseId: SellId, HouseType: 0 }, function (rows) {
                                $("#images", $win).empty();
                                for (var s = 0; s < rows.length; s++) {
                                    var tempObj = rows[s];
                                    var tempstr="<a class='fancybox-button' rel='fancybox-button' href='{1}' style='padding:2px;height:100px;width:78px;float:left;display:block' title='{2} <a href=\"/House/Services/House_Sells_Images.asmx/Download?path={3}\" style=\"color:#fff\" target=\"_blank\">下载</a>'><img src='{0}' style='height:100%;width:100%' title='{2}' /></div>".format(
                                        tempObj.ThumbImageUrl || '',
                                        tempObj.ImgUrl,
                                        tempObj.AddUser + " 上传于 " + tempObj.AddTime.toDate().format("yyyy-MM-dd hh:mm:ss"),
                                        tempObj.ImgUrl);
                                    $("#images", $win).append(tempstr);
                                }
                            });
                        }
                        //加载跟进
                        $.ajax({
                            type: "get",
                            url: "/House/Services/House_Sells_Follows.asmx/GetLists?t=" + Math.random(),
                            dataType: 'json',
                            data: { page: 1, rows: 200, txtSellId: SellId, tel: '' },
                            contentType: "application/json;utf-8",
                            success: function (data) {
                                var rows = loadFilter(data).rows;
                                if (rows) {
                                    for (var i = 0; i < rows.length; i++) {
                                        var row = rows[i];
                                        if (!row) continue;
                                        var _str = "<li>【{0}】[{1}][{3}]{2}</li>".format(row.AddUser,
                                         (row.AddTime.toDate()).format("yy-MM-dd hh:mm"),
                                         row.Follow,
                                         X_SELLSTATE[row.State]);
                                        $(".ulHouseSell", $win).append(_str);
                                    }
                                }
                            }
                        });

                    }
                }
            },
            buttons: buttons,
            listeners: {
                close: function () {
                }
            }
        }).show();
    }
});
